package controllers

import (
	"github.com/jinzhu/gorm"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"tizhi_front/model"
	"tizhi_front/nspel"
	"tizhi_front/response"
	"tizhi_front/utils"
)

type CourseController struct {
	Ctx iris.Context
}

func (c *CourseController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("POST", "/recommend_list", "RecommendCourseList", beforeCommonToken)
	b.Handle("POST", "/recommend_list/{Type:int}", "RecommendCourseListByType", beforeCommonToken)
	b.Handle("POST", "/list", "GetCourseList", beforeCommonToken)
	b.Handle("POST", "/list/{Type:int}/{offset:long}", "GetCourseListByType", beforeCommonToken)
	b.Handle("POST", "/detail/{id:long}", "GetCourseDetail", beforeCommonToken)
	b.Handle("POST", "/collect/{id:long}", "CourseCollect", beforeCommonToken)
	b.Handle("POST", "/like/{id:long}", "CourseLike", beforeCommonToken)
	b.Handle("POST", "/un_collect/{id:long}", "CourseUnCollect", beforeCommonToken)
	b.Handle("POST", "/un_like/{id:long}", "CourseUnLike", beforeCommonToken)
	b.Handle("POST", "/collect/list/{offset:long}", "GetCollectCourseListByType", beforeCommonToken)
}

// @Title Recommend Course List
// @Description 根据个人的测试情况推荐出个人的训练列表
// @Tags course
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.RecommendCourseList
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /course/recommend_list [post]
func (c *CourseController) RecommendCourseList() response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	courses, err := utils.GetCourseList(uid, -1)
	res := response.RecommendCourseList{}
	res.RecommendCourses = make([]response.CourseListInfo, len(courses))
	courseCollect := model.CourseCollectE{}
	var count int64
	for i := 0; i < len(courses); i++ {
		count, err = courseCollect.SelectCountByCourseId(courses[i].Id)
		if err != nil {
			nspel.Error(err)
			return response.JsonResponse{
				ErrCode: 2,
				ErrInfo: err.Error(),
				Data:    "",
			}
		}
		res.RecommendCourses[i] = response.CourseListInfo{
			Id:              courses[i].Id,
			Type:            int(courses[i].LabelId),
			VideoKey:        courses[i].VideoKey,
			VideoPic:        courses[i].VideoPic,
			VideoTimeLength: int(courses[i].VideoTimeLength),
			HardLevel:       int(courses[i].Difficulty),
			Participants:    count,
			ShopAddress:     courses[i].ShopAddress,
			CourseTitle:     courses[i].Name,
			Description:     courses[i].Description,
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}

// @Title Recommend Course List By Type
// @Description 根据个人的测试情况以及类型推荐出相应的全部训练课程
// @Tags course
// @Param	type path int64	true "type for course"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.RecommendCourseList
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /course/recommend_list/{type} [post]
func (c *CourseController) RecommendCourseListByType(Type int) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	courses, err := utils.GetCourseList(uid, int64(Type))
	res := response.RecommendCourseList{}
	res.RecommendCourses = make([]response.CourseListInfo, len(courses))
	courseCollect := model.CourseCollectE{}
	var count int64
	for i := 0; i < len(courses); i++ {
		count, err = courseCollect.SelectCountByCourseId(courses[i].Id)
		if err != nil {
			nspel.Error(err)
			return response.JsonResponse{
				ErrCode: 2,
				ErrInfo: err.Error(),
				Data:    "",
			}
		}
		res.RecommendCourses[i] = response.CourseListInfo{
			Id:              courses[i].Id,
			Type:            int(courses[i].LabelId),
			VideoKey:        courses[i].VideoKey,
			VideoPic:        courses[i].VideoPic,
			VideoTimeLength: int(courses[i].VideoTimeLength),
			HardLevel:       int(courses[i].Difficulty),
			Participants:    count,
			ShopAddress:     courses[i].ShopAddress,
			CourseTitle:     courses[i].Name,
			Description:     courses[i].Description,
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}

// @Title Get Course List
// @Description 获取课程列表
// @Tags course
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.CourseLists
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /course/list [post]
func (c *CourseController) GetCourseList() response.JsonResponse {
	course := model.CourseE{}
	courses, err := course.SelectAllOrderByLabelIdAsc()
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	res := response.CourseLists{
		CourseList: []response.CourseListWithType{},
	}
	lastLabelId := int64(-1)
	courseCollect := model.CourseCollectE{}
	var count int64
	for i := 0; i < len(courses); i++ {
		count, err = courseCollect.SelectCountByCourseId(courses[i].Id)
		if err != nil {
			nspel.Error(err)
			return response.JsonResponse{
				ErrCode: 2,
				ErrInfo: err.Error(),
				Data:    "",
			}
		}
		if courses[i].LabelId != lastLabelId {
			lastLabelId = courses[i].LabelId
			res.CourseList = append(res.CourseList, response.CourseListWithType{
				Type:            int(courses[i].LabelId),
				ShortShowCount:  3,
				PerRequestCount: 8,
				TotalCount:      1,
				Offset:          0,
				CourseList: []response.CourseListInfo{{
					Id:              courses[i].Id,
					Type:            int(courses[i].LabelId),
					VideoKey:        courses[i].VideoKey,
					VideoPic:        courses[i].VideoPic,
					VideoTimeLength: int(courses[i].VideoTimeLength),
					HardLevel:       int(courses[i].Difficulty),
					Participants:    count,
					ShopAddress:     courses[i].ShopAddress,
					CourseTitle:     courses[i].Name,
					Description:     courses[i].Description,
				}},
			})
		} else {
			res.CourseList[len(res.CourseList)-1].TotalCount++
			if len(res.CourseList[len(res.CourseList)-1].CourseList) < 3 {
				res.CourseList[len(res.CourseList)-1].CourseList = append(res.CourseList[len(res.CourseList)-1].CourseList, response.CourseListInfo{
					Id:              courses[i].Id,
					Type:            int(courses[i].LabelId),
					VideoKey:        courses[i].VideoKey,
					VideoPic:        courses[i].VideoPic,
					VideoTimeLength: int(courses[i].VideoTimeLength),
					HardLevel:       int(courses[i].Difficulty),
					Participants:    count,
					ShopAddress:     courses[i].ShopAddress,
					CourseTitle:     courses[i].Name,
					Description:     courses[i].Description,
				})
			}
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}

// @Title Get Course List By Type
// @Description 获取课程列表
// @Tags course
// @Param	offset path int64	true "offset for list"
// @Param	type path int	true "type for course, //0:力量、1:速度、2:耐力、3:协调、4:柔韧、5:灵敏"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.CourseList
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /course/list/{type}/{offset} [post]
func (c *CourseController) GetCourseListByType(Type int, offset int64) response.JsonResponse {
	course := model.CourseE{}
	courses, err := course.SelectAllByLabelId(int64(Type))
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	res := response.CourseList{
		Offset:          offset,
		ShortShowCount:  3,
		PerRequestCount: 8,
		TotalCount:      int64(len(courses)),
		CourseList:      []response.CourseListInfo{},
	}
	courseCollect := model.CourseCollectE{}
	var count int64
	for i := offset; i < int64(len(courses)) && i < offset+8; i++ {
		count, err = courseCollect.SelectCountByCourseId(courses[i].Id)
		if err != nil {
			nspel.Error(err)
			return response.JsonResponse{
				ErrCode: 2,
				ErrInfo: err.Error(),
				Data:    "",
			}
		}
		res.CourseList = append(res.CourseList, response.CourseListInfo{
			Id:              courses[i].Id,
			Type:            int(courses[i].LabelId),
			VideoKey:        courses[i].VideoKey,
			VideoPic:        courses[i].VideoPic,
			VideoTimeLength: int(courses[i].VideoTimeLength),
			HardLevel:       int(courses[i].Difficulty),
			Participants:    count,
			ShopAddress:     courses[i].ShopAddress,
			CourseTitle:     courses[i].Name,
			Description:     courses[i].Description,
		})
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}

// @Title Course Detail
// @Description 根据Id获取课程详情
// @Tags course
// @Param	id path int64	true "id for course"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object}	response.CourseDetail response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /course/detail/{id} [post]
func (c *CourseController) GetCourseDetail(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	course := model.Course1{}
	err = course.SelectById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	courseCollect := model.CourseCollectE{}
	count, err := courseCollect.SelectCountByCourseId(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	res := response.CourseDetail{
		CourseListInfo: response.CourseListInfo{
			Id:              id,
			Type:            int(course.LabelId),
			VideoKey:        course.VideoKey,
			VideoPic:        course.VideoPic,
			VideoTimeLength: int(course.VideoTimeLength),
			Participants:    count,
			HardLevel:       int(course.Difficulty),
			ShopAddress:     course.ShopAddress,
			CourseTitle:     course.Name,
			Description:     course.Description,
		},
		CourseDetailInfo: response.CourseDetailInfo{
			PicPath:            course.PicUrl,
			RecommendTrainTime: int(course.TrainTime),
			DetailInfo:         course.DetailDescription,
		},
	}
	courseLike := model.CourseLikeE{}
	err = courseLike.SelectByStudentIdCourseId(uid, id)
	if err != gorm.ErrRecordNotFound && err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err == nil {
		res.Like = true
	}
	err = courseCollect.SelectByStudentIdCourseId(uid, id)
	if err != gorm.ErrRecordNotFound && err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err == nil {
		res.Collect = true
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}

// @Title Course Collect
// @Description 根据Id,添加到收藏
// @Tags course
// @Param	id path int64	true "id for Course"
// @Param	body body response.TokenInfo	true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @Failure 3 {string} string "已经收藏，无需重复收藏"
// @router /course/collect/{id} [post]
func (c *CourseController) CourseCollect(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	course := model.Course2{}
	err = course.SelectById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	courseCollect := model.CourseCollectE{}
	err = courseCollect.SelectByStudentIdCourseId(uid, id)
	if err != gorm.ErrRecordNotFound && err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err == nil {
		return response.JsonResponse{
			ErrCode: 3,
			ErrInfo: "已经收藏，无需重复收藏",
			Data:    "",
		}
	}
	courseCollect1 := model.CourseCollect1{
		StudentId: uid,
		CourseId:  id,
	}
	err = courseCollect1.Insert()
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	utils.NewMessage(uid, "收藏课程成功")
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Course Like
// @Description 根据Id,添加到喜欢
// @Tags course
// @Param	id path int64	true "id for Course"
// @Param	body body response.TokenInfo	true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @Failure 3 {string} string "已经喜欢，无需重复喜欢"
// @router /course/like/{id} [post]
func (c *CourseController) CourseLike(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	course := model.Course2{}
	err = course.SelectById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	courseLike := model.CourseLikeE{}
	err = courseLike.SelectByStudentIdCourseId(uid, id)
	if err != gorm.ErrRecordNotFound && err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err == nil {
		return response.JsonResponse{
			ErrCode: 3,
			ErrInfo: "已经喜欢，无需重复喜欢",
			Data:    "",
		}
	}
	courseLike1 := model.CourseLike1{
		StudentId: uid,
		CourseId:  id,
	}
	err = courseLike1.Insert()
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	utils.NewMessage(uid, "喜欢课程成功")
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Course UnCollect
// @Description 根据Id,去除收藏
// @Tags course
// @Param	id path int64	true "id for Course"
// @Param	body body response.TokenInfo	true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @Failure 3 {string} string "没有收藏，无法去除收藏"
// @router /course/un_collect/{id} [post]
func (c *CourseController) CourseUnCollect(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	course := model.Course2{}
	err = course.SelectById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	courseCollect := model.CourseCollect0{}
	err = courseCollect.SelectByStudentIdCourseId(uid, id)
	if err != gorm.ErrRecordNotFound && err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err != nil {
		return response.JsonResponse{
			ErrCode: 3,
			ErrInfo: "没有收藏，无法去除收藏",
			Data:    "",
		}
	}
	err = courseCollect.Delete(uid, id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Course UnLike
// @Description 根据Id,去除喜欢
// @Tags course
// @Param	id path int64	true "id for Course"
// @Param	body body response.TokenInfo	true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @Failure 3 {string} string "没有喜欢，无法去除喜欢"
// @router /course/un_like/{id} [post]
func (c *CourseController) CourseUnLike(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	course := model.Course2{}
	err = course.SelectById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	courseLike := model.CourseLike0{}
	err = courseLike.SelectByStudentIdCourseId(uid, id)
	if err != gorm.ErrRecordNotFound && err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err != nil {
		return response.JsonResponse{
			ErrCode: 3,
			ErrInfo: "没有喜欢，无法去除喜欢",
			Data:    "",
		}
	}
	err = courseLike.Delete(uid, id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Get Collect Course List
// @Description 获取收藏课程列表
// @Tags course
// @Param	offset path int64	true "offset for list"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.CourseList
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /course/collect/list/{offset} [post]
func (c *CourseController) GetCollectCourseListByType(offset int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	courseCollect := model.CourseCollectE{}
	courseCollects, err := courseCollect.SelectAllByStudentId(uid)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	id := make([]int64, len(courseCollects))
	for i := 0; i < len(courseCollects); i++ {
		id[i] = courseCollects[i].CourseId
	}
	course := model.CourseE{}
	courses, err := course.SelectAllById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	res := response.CourseList{
		Offset:          offset,
		ShortShowCount:  3,
		PerRequestCount: 8,
		TotalCount:      int64(len(courses)),
		CourseList:      []response.CourseListInfo{},
	}
	var count int64
	for i := offset; i < int64(len(courses)) && i < offset+8; i++ {
		count, err = courseCollect.SelectCountByCourseId(courses[i].Id)
		if err != nil {
			nspel.Error(err)
			return response.JsonResponse{
				ErrCode: 2,
				ErrInfo: err.Error(),
				Data:    "",
			}
		}
		res.CourseList = append(res.CourseList, response.CourseListInfo{
			Id:              courses[i].Id,
			Type:            int(courses[i].LabelId),
			VideoKey:        courses[i].VideoKey,
			VideoPic:        courses[i].VideoPic,
			VideoTimeLength: int(courses[i].VideoTimeLength),
			HardLevel:       int(courses[i].Difficulty),
			Participants:    count,
			ShopAddress:     courses[i].ShopAddress,
			CourseTitle:     courses[i].Name,
			Description:     courses[i].Description,
		})
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}
